<template>
  <van-nav-bar title="菜谱详情" style="position: sticky;top:0;" left-text="返回" left-arrow
    @click-left="() => { router.back() }">
    <template v-if="isShow || isHavePermission" #right>
      <i class="iconfont icon-top" @click="deleteCook"></i>
    </template></van-nav-bar>
  <div class=" cook">
    <div class="img">
      <img :src=cookData.image alt="">
    </div>
    <div class="cook-msg">
      <div class="cook-msg-name">{{ cookData.name }}</div>
      <div class="cook-msg-time-like">
        <div class="time">
          <i class="iconfont icon-shijian1"></i> {{ cookData.time }} 分钟
        </div>
        <div class="like" @click="addLike(cookData.id)">
          <i class="iconfont icon-shoucang1" :style="{ color: isRed ? 'red' : '' }"></i> {{ cookData.likeNum }} 收藏
        </div>
      </div>
    </div>
    <div class="author">
      <div class="author-avatar">
        <img :src=cookData.avatar alt="">
      </div>
      <div class="author-msg">
        <div class="author-msg-nickname">{{ cookData.nickName }}</div>
        <div class="author-msg-publishTime">{{ formatDateHour(cookData.publishTime) }} 发布</div>
      </div>
    </div>
    <div class="material">
      <div class="material-title">用料</div>
      <div class="material-content">
        <div v-for="(item, index) in cookData.materials" class="material-content-item">
          <div class="material-content-item-name">{{ item.name }}</div>
          <div class="material-content-item-num">{{ item.quantity }}</div>
        </div>
      </div>
    </div>
    <div class="step">
      <div class="step-title">烹饪步骤</div>
      <div class="step-content">
        <div v-for="(item, index) in cookData.steps" class="step-content-item">
          <div class="step-content-item-number">
            {{ index + 1 }}
          </div>
          <div class="step-content-item-msg">
            <div class="step-content-item-msg-detail">{{ item.description }}</div>
            <div class="step-content-item-msg-img">
              <img :src=item.image alt="">
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="tip">
      <div class="tip-title">烹饪心得</div>
      <div class="tip-content">
        {{ cookData.tips }}
      </div>
    </div>
    <div v-if="isDraft" class="operator">
      <van-button type="default" class="buttonDetail" @click="keepEdit">继续编辑</van-button>
      <van-button type="primary" class="buttonDetail" color="#FF9966" @click="publish(1)">立即发布</van-button>
    </div>
    <div v-if="showLookComment" class="look-comment" @click="getComment">查看评论</div>
    <div v-if="showComment" class="comment">
      <div class="comment-title">
        <div class="title">评论</div>
        <div class="order" @click="selectOrder"><i class="iconfont icon-pinglun"></i></div>
      </div>
      <div v-for="(item, index) in commentData" class="item">
        <div class="item-avatar">
          <img :src=item.avatar alt="">
        </div>
        <div class="item-msg">
          <div class="item-msg-top">
            <div class="item-msg-top-user">
              <div class="item-msg-top-user-nickname">{{ item.nickName }}</div>
              <div class="item-msg-top-user-commentTime">{{ formatDateHour(item.create_time) }}</div>
            </div>
            <!-- <div class="comment-item-goods"><i class="iconfont icon-dianzan"></i>23</div> -->
          </div>
          <div class="item-msg-content">
            {{ item.content }}
          </div>
        </div>
      </div>
    </div>
  </div>
  <van-loading v-if="showLoading" style="text-align: center;" type="spinner" color="#1989fa" />
  <van-popup v-model:show="showBottom" position="bottom" :style="{ height: '40px' }">
    <div class="input-comment">
      <van-field class="input-comment-content" v-model="commentInfo" placeholder="请发表你的评论" />
      <van-button class="input-btn" @click="handleComment" color="#FF9966">评论</van-button>
    </div>
  </van-popup>
</template>

<script setup>
import { onMounted, ref, } from 'vue'
import router from '@/router/index.js'
import { useRoute } from 'vue-router'
import { getCommonById, getCommentById, postComment, addMyLike, isLike, deteleLike, changePublish, deleteMyCook } from '@/api/index.js'
import { formatDateHour } from '@/utils/formateDate.js'
import { getUserId } from "@/utils/getUserId";
import { showToast, showSuccessToast, showFailToast, showConfirmDialog } from 'vant'
import { checkPermission, checkUser } from '@/utils/isLogin.js';
const showBottom = ref(false)
const route = useRoute()
const showComment = ref(false)
const showLookComment = ref(true)
const showLoading = ref(false)
const commentData = ref({})
const cookData = ref({})
const commentInfo = ref('')
const isRed = ref(false)
const isDraft = ref(false)
const comment = ref({
  create_time: '',
  commonId: Number(route.query.id),
  userId: getUserId(),
  content: '',
})
const isShow = ref(false)
const status = ref('publish')   // 判断是否为已发布还是草稿，用于删除文案

const isHavePermission = ref(false)

onMounted(async () => {
  if (await checkUser('admin')) {
    isHavePermission.value = true
  }

  const id = route.query.id
  const res = await getCommonById(id);
  cookData.value = res.data[0]
  status.value = cookData.value.status === 1 ? 'publish' : 'draft';

  const isTrue = await checkUser('user')
  if (cookData.value.authorId === getUserId() && isTrue) {
    isShow.value = true
  }
  if (cookData.value.status === 0) {
    showLookComment.value = false
    isDraft.value = true
  } else {
    isDraft.value = false
  }
  const params = { cookId: id, userId: getUserId() }
  const result = await isLike(params)

  isRed.value = result.flag
})

const selectOrder = () => {
  showBottom.value = true
}

const validateForm = (flag) => {
  const { name, image, time, materials, steps, tips } = cookData.value;
  // 如果是发布，则继续校验其他字段
  if (flag === 1) {
    if (!name || !image || !time || materials.length === 0 || steps.length === 0 || !tips) {
      showToast('信息不完整，请继续编辑')
      return false;
    }
  }

  return true;
};

const getComment = async () => {
  showLookComment.value = false
  showLoading.value = true
  const id = route.query.id
  // 根据id查找
  const res = await getCommentById(id)
  if (res) {
    showComment.value = true
    showLoading.value = false
    commentData.value = res.data
  }
}

// 收藏
const addLike = async (cookId) => {
  if (!await checkPermission()) {
    return
  }
  const param = { cookId, userId: getUserId() }
  const res = await addMyLike(param)
  if (res.flag) {
    cookData.value.likeNum += 1
    showSuccessToast(`${res.message}`)
    isRed.value = true
  } else {
    showConfirmDialog({
      message:
        '您已收藏，确认取消吗？',
    })
      .then(async () => {
        const res = await deteleLike(param)
        if (res) {
          cookData.value.likeNum -= 1
          showSuccessToast(`已取消收藏`)
          isRed.value = false
        }
      })
      .catch(() => {
        // on cancel
      });
  }
}

const handleComment = async () => {
  if (!await checkPermission()) {
    return
  }
  if (!commentInfo.value || commentInfo.value.trim() === '') {
    showToast('评论不能为空')
    return
  }
  comment.value.create_time = Date.now()
  comment.value.content = commentInfo.value
  const param = comment.value
  const res = await postComment(param)
  if (res) {
    showSuccessToast(`${res.message}`)
  } else {
    showFailToast(`${res.message}`)
  }
  showBottom.value = false
  await getComment()
}

const keepEdit = async () => {
  if (!await checkPermission()) {
    return
  }
  router.push({ path: '/editCook', query: { id: `${route.query.id}` } })
}

// 跳到草稿箱，如果要发布，直接将该条数据的status改为1
const publish = async (flag) => {
  if (!await checkPermission()) {
    return
  }
  // 先进行表单校验
  if (!validateForm(flag)) {
    return;
  }

  showConfirmDialog({
    message:
      '确认直接发布吗？',
  })
    .then(async () => {
      const id = route.query.id
      const publishTime = Date.now()
      const res = await changePublish(id, publishTime);
      if (res) {
        showSuccessToast(`${res.message}`)
        router.push({ path: '/community' })
      } else {
        showFailToast(`${res.message}`)
      }
    })
    .catch(() => {
      // on cancel
    });
}

const deleteCook = async () => {
  if (!await checkPermission()) {
    return
  }
  showConfirmDialog({
    message: status.value === 'publish'
      ? '确认删除该发布的菜谱吗？'
      : '确认删除该草稿中的菜谱吗？',
  })
    .then(async () => {
      const res = await deleteMyCook(route.query.id)
      if (res.code === 200) {
        showSuccessToast('删除成功')
        router.push({ path: '/menu' })
      }
    })
    .catch(() => {
      return
    });
}
</script>

<style lang="less" scoped>
.cook {
  background-color: rgb(238, 240, 244);

  .img {
    width: 9rem;
    height: 9rem;
    margin-bottom: 6px;
    padding: 8px 0.5rem;

    img {
      width: 100%;
      border-radius: 8px;
    }
  }

  &-msg {
    padding: 14px 0.5rem;
    background-color: #fff;
    border-radius: 8px;

    &-name {
      height: 20px;
      font-size: 20px;
      line-height: 20px;
    }

    &-time-like {
      margin-top: 8px;
      font-size: 14px;
      display: flex;

      .time {
        margin-right: 16px;
      }
    }
  }

  .author {
    margin-top: 8px;
    height: 40px;
    background-color: #fff;
    padding: 14px 0.5rem;
    display: flex;
    align-items: center;
    border-radius: 8px;

    &-avatar {
      width: 40px;
      height: 40px;
      margin-right: 20px;

      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
    }

    &-msg {
      font-size: 14px;

      &-publishTime {
        margin-top: 8px;
        font-size: 12px;
      }
    }
  }

  .material {
    background: #fff;
    font-size: 16px;
    margin-top: 6px;

    &-title {
      padding: 6px 8px;
    }

    &-content {
      padding: 8px 30px;

      &-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
      }
    }
  }

  .step {
    background: #fff;
    font-size: 16px;
    margin-top: 6px;
    padding: 6px 8px;


    &-content {
      margin-top: 14px;

      &-item {
        display: flex;
        margin-top: 14px;

        &-number {
          width: 24px;
          height: 24px;
          text-align: center;
          line-height: 24px;
          font-weight: 500;
          background-color: #FF9966;
          color: #fff;
          margin-right: 12px;
          border-radius: 50%;
        }

        &-msg {
          width: 8rem;
          line-height: 24px;

          &-img {
            width: 100%;

            img {
              margin-top: 8px;
              width: 100%;
              border-radius: 8px;
            }
          }
        }
      }
    }
  }

  .tip {
    background: #fff;
    font-size: 16px;
    margin-top: 6px;
    padding: 8px;

    &-title {
      padding: 6px 8px;
    }

    &-content {
      padding: 8px 16px;
      background-color: #dee2e8;
      margin-top: 4px 8px;
      border-radius: 8px;
      line-height: 20px;
      font-size: 14px;
    }
  }

  .look-comment {
    height: 40px;
    line-height: 40px;
    font-size: 16px;
    text-align: center;
    background-color: #FF9966;
    font-weight: 500;
    color: #fff;
    border-radius: 8px;
  }

  .operator {
    display: grid;
    margin-top: 8px;
    grid-template-columns: 1fr 1fr;
  }

  .comment {
    background: #fff;
    font-size: 14px;
    margin-top: 6px;
    padding: 8px;

    &-title {
      padding: 6px 8px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .order {
        font-size: 14px;

        .iconfont {
          font-size: 18px;
        }
      }
    }

    .item {
      display: flex;
      margin-bottom: 16px;

      &-avatar {
        width: 30px;
        height: 30px;
        margin-right: 8px;
        flex-shrink: 0;

        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }
      }

      &-msg {

        &-top {
          display: flex;
          height: 30px;
          justify-content: space-between;
          align-items: center;

          &-user {
            &-commentTime {
              color: rgb(93, 87, 87);
              font-size: 12px;
              margin-top: 4px;
            }
          }

        }

        &-content {
          margin-top: 4px;
          font-size: 13px;
          line-height: 16px;
        }
      }
    }


  }

}

.input-comment {
  position: fixed;
  bottom: 0;
  width: 98%;
  display: flex;
  height: 30px;
  border: 1px solid #FF9966;
  padding: 2px;

  .input-btn {
    width: 80px;
    height: 30px;
  }

  &-content {
    height: 30px;
    padding: 4px 8px;
  }
}
</style>